import { Text, View } from '@tarojs/components';
import Navbar from '@/components/Navbar';
import { TextArea, Uploader } from '@nutui/nutui-react-taro';
import { useState } from 'react';
import './index.less';
import ButtonComp from '@/components/Button';
import ImageConstant from '@/constant/ImageConstant';
import { getCurrentInstance, navigateBack, showToast } from '@tarojs/taro';
import authStore from '@/stores/AuthStore';
import CodeConstant from '@/constant/CodeConstant';
import HouseReportBusiness from '@/business/HouseReportBusiness';
import useReport from '@/hooks/useReport';
import userStore from '@/stores/UserStore';
import socketStore from '@/stores/SocketStore';
import AuthConstant from '@/constant/AuthConstant';
import BusinessConstant from '@/constant/BusinessConstant';

const Maintenance = () => {
  const {getReportByTenantId} = useReport();
  const {user} = userStore;
  const {websocketInstance} = socketStore;
  const routerParams = getCurrentInstance().router?.params;
  const [reason, setReason] = useState('');
  const [imgList, setImgList] = useState<Array<string>>([]);
  const [video, setVideo] = useState('');

  /**
   * 维修图片上传成功回调
   */
  const maintenanceImgUploadSuccess = ({responseText}) => {
    const res: any = JSON.parse(responseText.data);
    if (res.code !== CodeConstant.SUCCESS) {
      showToast({title: '图片上传失败！', icon: 'error'});
      return;
    }
    showToast({title: '图片上传成功！', icon: 'success'});
    setImgList(imgList => [...imgList, res.data]);
  };

  /**
   * 维修视频上传成功回调
   */
  const maintenanceVideoUploadSuccess = ({responseText}) => {
    const res: any = JSON.parse(responseText.data);
    if (res.code !== CodeConstant.SUCCESS) {
      showToast({title: '视频上传失败！', icon: 'error'});
      return;
    }
    showToast({title: '视频上传成功！', icon: 'success'});
    setVideo(res.data);
  };

  /**
   * 提交房屋维修
   */
  const submitMaintenance = async () => {
    if (!reason) {
      showToast({
        title: '问题描述不允许为空！',
        icon: 'error'
      });
    }
    if (!routerParams?.houseId) {
      showToast({
        title: '房屋id不存在！',
        icon: 'error'
      });
      return;
    }
    await HouseReportBusiness.addReport({
      reason,
      image: JSON.stringify(imgList),
      video: video,
      houseId: Number(routerParams.houseId),
      landlordId: Number(routerParams.landlordId),
      tenantId: user.id
    });
    // 重新获取租客的房屋维修信息
    await getReportByTenantId(user.id!);
    // 向房东发送维修消息
    websocketInstance && websocketInstance.send({
      data: JSON.stringify({
        toIdentity: AuthConstant.LANDLORD,
        toId: Number(routerParams.landlordId),
        active: BusinessConstant.SOCKET_GET_LANDLORD_REPORT
      })
    });
    navigateBack();
    showToast({
      title: '提交成功',
      icon: 'success'
    });
  };

  return (
    <Navbar
      mode='back'
      title='房屋报修'
      bgColor='var(--mini-first)'
    >
      <View className='maintenance-container'>
        <View className='reason-text-wrap'>
          <Text style={ {whiteSpace: 'nowrap'} }>问题描述：</Text>
          <TextArea
            className='reason-textarea'
            value={ reason }
            onChange={ (val) => setReason(val) }
            showCount
            placeholder='请输入遇到的问题'
          />
        </View>
        <View className='reason-img-wrap'>
          <Text style={ {whiteSpace: 'nowrap'} }>问题图片：</Text>
          <Uploader
            maxCount={ 3 }
            multiple={ true }
            url={ ImageConstant.UPLOAD_IMG_VIDEO }
            headers={ {authorization: authStore.token} }
            onSuccess={ maintenanceImgUploadSuccess }
          />
        </View>
        <View className='reason-video-wrap'>
          <Text>问题视频：</Text>
          <Uploader
            sourceType={ ['camera'] }
            maxDuration={ 5 }
            url={ ImageConstant.UPLOAD_IMG_VIDEO }
            previewUrl={ `${ ImageConstant.SERVER_ROOT }${ ImageConstant.DEFAULT_VIDEO_COVER_IMG }` }
            headers={ {authorization: authStore.token} }
            onSuccess={ maintenanceVideoUploadSuccess }
          />
        </View>
        <ButtonComp
          title='提交'
          bgColor='var(--mini-first)'
          className='submit-btn'
          size='large'
          onClick={ submitMaintenance }
        />
      </View>
    </Navbar>
  );
};

export default Maintenance;